package com.didd.core.dict.core;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取字典数据的抽象父类 <br>
 *     默认实现了对枚举类映射的方法
 *     根据需要自定义根据dictCode查询字典的方法
 *     根据需要自定义根据dicTable, dictCode查询字典的方法
 *     集成的服务中如要对BaseEntityDictService进行实现，EntityDictUtil才能找到entityDictService
 *
 * @author diddd
 * @date: 2021-07-28 10:20:06
 */
public abstract class BaseEntityDictService implements EntityDictService {
    private static final Logger log = LoggerFactory.getLogger(BaseEntityDictService.class);
    @Override
    public Map<String, String> queryDict(String dicTable, String dictCode, Class<? extends DictEnumInterface> enumClass) {
        Map<String, String> dictMap = new HashMap<>();
        if (enumClass != null) {
            dictMap = queryByEnum(enumClass);
        } else if (StringUtils.isEmpty(dicTable)) {
            dictMap = queryByDictCode(dictCode);
        } else if (!StringUtils.isEmpty(dicTable) && !StringUtils.isEmpty(dictCode)) {
            dictMap = queryByDictTable(dicTable, dictCode);
        }
        return dictMap;
    }

    public Map<String, String> queryByEnum(Class<? extends DictEnumInterface> enumClass) {
        Map<String, String> dictMap = new HashMap<>();
        try {
            Class dictEnum = Class.forName(enumClass.getName());

            Method valuesMethod = dictEnum.getMethod("values");
            DictEnumInterface[] values = (DictEnumInterface[]) valuesMethod.invoke(dictEnum);
            for (int i = 0; i < values.length; i++) {
                DictEnumInterface v = values[i];
                dictMap.put(v.getCode(), v.getName());
            }
        } catch (Exception e) {
            log.error("进行字段映射时出现异常", e);
        }
        return dictMap;
    }

    public abstract Map<String, String> queryByDictCode(String dictCode);

    public abstract Map<String, String> queryByDictTable(String dicTable, String dictCode);

}
